package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.domain.PmsPrOperationLogs;
import com.ruoyi.system.domain.PmsPurchaseRequisitions;
import com.ruoyi.system.domain.PmsPurchaseRequisitionsDetail;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.bo.PmsPrOperationLogsBo;
import com.ruoyi.system.enums.PurchaseRequisitionStatus;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IPmsPrOperationLogsService;
import com.ruoyi.system.utils.GetOrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IPmsPurchaseRequisitionsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购申请单主Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-08
 */
@Service
public class PmsPurchaseRequisitionsServiceImpl implements IPmsPurchaseRequisitionsService
{
    @Autowired
    private PmsPurchaseRequisitionsMapper pmsPurchaseRequisitionsMapper;
    @Autowired
    private PmsPurchaseRequisitionsDetailMapper pmsPurchaseRequisitionsDetailMapper;
    @Autowired
    private GetOrderNoUtil getOrderNoUtil;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private PmsPrOperationLogsMapper pmsPrOperationLogsMapper;

    @Autowired
    private IPmsPrOperationLogsService pmsPrOperationLogsService;

    @Autowired
    private SysPostMapper sysPostMapper;

    /**
     * 查询采购申请单主
     *
     * @param prId 采购申请单主主键
     * @return 采购申请单主
     */
    @Override
    public PmsPurchaseRequisitions selectPmsPurchaseRequisitionsByPrId(Long prId)
    {
        return pmsPurchaseRequisitionsMapper.selectPmsPurchaseRequisitionsByPrId(prId);
    }

    /**
     * 查询采购申请单主列表
     *
     * @param pmsPurchaseRequisitions 采购申请单主
     * @return 采购申请单主
     */
    @Override
    public TableDataInfo<PmsPurchaseRequisitions> selectPmsPurchaseRequisitionsList(PmsPurchaseRequisitions pmsPurchaseRequisitions, PageQuery pageQuery)
    {
        //判断是不是财务部的
        SysDept sysDept = sysDeptMapper.selectById(LoginHelper.getDeptId());
        if("FINANCE".equals(sysDept.getDeptCode())){
            pmsPurchaseRequisitions.setDeptId(LoginHelper.getDeptId());
            return TableDataInfo.build( pmsPurchaseRequisitionsMapper.selectPmsPurchaseRequisitionsByFinanceList(pageQuery.build(),pmsPurchaseRequisitions));
        }


        //判断是否是管理员
        if(LoginHelper.getUserId() == 1L){
            pmsPurchaseRequisitions.setIsAdmin(true);
        }else {
            pmsPurchaseRequisitions.setRequesterId(LoginHelper.getUserId());
            pmsPurchaseRequisitions.setDepartmentId(LoginHelper.getDeptId());
        }

        //获取当前用户是否是领导
        List<SysPost> postList = sysPostMapper.selectPostsByUserId(LoginHelper.getUserId());
        for (SysPost sysPost : postList) {
            if("1".equals(sysPost.getIsLeader())){
                pmsPurchaseRequisitions.setIsLeader(true);
                break;
            }
        }


        Page<PmsPurchaseRequisitions> page = pmsPurchaseRequisitionsMapper.selectPmsPurchaseRequisitionsList(pageQuery.build(), pmsPurchaseRequisitions);
        return TableDataInfo.build(page);
    }

    /**
     * 新增采购申请单主
     *
     * @param pmsPurchaseRequisitions 采购申请单主
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPmsPurchaseRequisitions(PmsPurchaseRequisitions pmsPurchaseRequisitions)
    {
        pmsPurchaseRequisitions.setRequestDate(new Date());
        int i = pmsPurchaseRequisitionsMapper.insertPmsPurchaseRequisitions(pmsPurchaseRequisitions);
        for (PmsPurchaseRequisitionsDetail pmsPurchaseRequisitionsDetail : pmsPurchaseRequisitions.getPmsPurchaseRequisitionsDetails()){
            pmsPurchaseRequisitionsDetail.setPurchaseRequistionsId(pmsPurchaseRequisitions.getPrId());
            pmsPurchaseRequisitionsDetail.setCreateTime(new Date());
            pmsPurchaseRequisitionsDetailMapper.insertPmsPurchaseRequisitionsDetail(pmsPurchaseRequisitionsDetail);
        }

        //并且新增采购申请单操作日志表
        pmsPurchaseRequisitions.setStatus(pmsPurchaseRequisitions.getStatus());
        try{
            pmsPrOperationLogsMapper.delete(new LambdaQueryWrapper<PmsPrOperationLogs>()
            .eq(PmsPrOperationLogs::getPrId,pmsPurchaseRequisitions.getPrId())
            .eq(PmsPrOperationLogs::getOperationType,pmsPurchaseRequisitions.getStatus()));
            pmsPrOperationLogsService.initializePmsPrOperationLogsBo(pmsPurchaseRequisitions);
        }catch (Exception e){
            throw new RuntimeException(e); // 转换为非检查型异常
        }
        return i;
    }



    /**
     * 修改采购申请单主
     *
     * @param pmsPurchaseRequisitions 采购申请单主
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePmsPurchaseRequisitions(PmsPurchaseRequisitions pmsPurchaseRequisitions)
    {
        int i = pmsPurchaseRequisitionsMapper.updatePmsPurchaseRequisitions(pmsPurchaseRequisitions);

        pmsPurchaseRequisitionsDetailMapper.deletePmsPurchaseRequisitionsDetailByPurchaseRequistionsId(pmsPurchaseRequisitions.getPrId());


        pmsPurchaseRequisitions.getPmsPurchaseRequisitionsDetails().forEach(pmsPurchaseRequisitionsDetail -> {
            pmsPurchaseRequisitionsDetail.setPurchaseRequistionsId(pmsPurchaseRequisitions.getPrId());
            pmsPurchaseRequisitionsDetail.setCreateTime(new Date());
            pmsPurchaseRequisitionsDetailMapper.insertPmsPurchaseRequisitionsDetail(pmsPurchaseRequisitionsDetail);
        });

        //并且新增采购申请单操作日志表
        pmsPrOperationLogsMapper.delete(new LambdaQueryWrapper<PmsPrOperationLogs>()
            .eq(PmsPrOperationLogs::getPrId,pmsPurchaseRequisitions.getPrId())
            .eq(PmsPrOperationLogs::getOperationType,pmsPurchaseRequisitions.getStatus()));
        pmsPurchaseRequisitions.setStatus(pmsPurchaseRequisitions.getStatus());
        pmsPrOperationLogsService.initializePmsPrOperationLogsBo(pmsPurchaseRequisitions);
        return i;
    }

    /**
     * 批量删除采购申请单主
     *
     * @param prIds 需要删除的采购申请单主主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePmsPurchaseRequisitionsByPrIds(Long[] prIds)
    {
        int j=0;
        for(int i=0;i<prIds.length;i++){
            Long prId = prIds[i];
            pmsPurchaseRequisitionsMapper.deletePmsPurchaseRequisitionsByPrId(prId);
            pmsPurchaseRequisitionsDetailMapper.deletePmsPurchaseRequisitionsDetailByPrId(prId);
            pmsPrOperationLogsMapper.delete(new LambdaQueryWrapper<PmsPrOperationLogs>()
                .eq(PmsPrOperationLogs::getPrId,prId));
            j++;
        }
        return j;
    }

    /**
     * 删除采购申请单主信息
     *
     * @param prId 采购申请单主主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePmsPurchaseRequisitionsByPrId(Long prId)
    {
        pmsPurchaseRequisitionsMapper.deletePmsPurchaseRequisitionsByPrId(prId);
        pmsPurchaseRequisitionsDetailMapper.deletePmsPurchaseRequisitionsDetailByPrId(prId);
        return pmsPrOperationLogsMapper.delete(new LambdaQueryWrapper<PmsPrOperationLogs>()
        .eq(PmsPrOperationLogs::getPrId,prId));
    }

    /**
     * 获取采购申请单信息
     * @return
     */
    @Override
    public PmsPurchaseRequisitions getPurchaseRequisitionsData() {
        PmsPurchaseRequisitions pmsPurchaseRequisitions = new PmsPurchaseRequisitions();
        pmsPurchaseRequisitions.setPrCode(getOrderNoUtil.getOrderNo("PR-"));

        Long userId = LoginHelper.getUserId();

        pmsPurchaseRequisitions.setRequesterId(userId);

        SysUser sysUser = sysUserMapper.selectUserById(userId);

        pmsPurchaseRequisitions.setDepartmentId(sysUser.getDeptId());

        pmsPurchaseRequisitions.setNickName(sysUser.getNickName());

        SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
        pmsPurchaseRequisitions.setDeptName(sysDept.getDeptName());

        return pmsPurchaseRequisitions;
    }

}
